//
//  FLinkedInViewController.m
//  WondrApp
//
//  Created by SDS on 10/22/12.
//  Copyright (c) 2012 SDS. All rights reserved.
//

#import "WTwitterViewController.h"
#import "OAMutableURLRequest.h"
#import "Constant.h"
#import "AFJSONRequestOperation.h"
#import "OARequestParameter.h"
@interface WTwitterViewController () {
    MBProgressHUD *progressHUD;
}
@end

@implementation WTwitterViewController
@synthesize webBrowser;
#pragma mark - Managing the detail item

#define MAX_MESSAGE_LENGTH 140

- (void)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
    if (!status) {
        return;
    }
     
    NSString *trimmedText = status;
    if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
        trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    [params setObject:trimmedText forKey:@"status"];
    if (updateID > 0) {
        [params setObject:[NSString stringWithFormat:@"%u", updateID] forKey:@"in_reply_to_status_id"];
    }
//    
  OAMutableURLRequest  *request=   [rdEngine sendAPIRequestWithURL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"] HTTPMethod:@"POST" body:nil];   
   OARequestParameter *requestParameter = [[OARequestParameter alloc] initWithName:@"status" value:@"test+fsd+sd+fsd+fsd+fsd+fds+fds+fsasd"];
    [request setHTTPMethod:@"POST"];
    [request setParameters:[NSArray arrayWithObject:requestParameter]];
    //OAMutableURLRequest * request = [rdEngine profileForCurrentUser];
    
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"%@", JSON);
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"%@",error); 
    }];
    
    [operation start];
;
//    
//    OAMutableURLRequest *request = [rdEngine profileForCurrentUser];
//    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//        NSString *twitterID = [JSON objectForKey:@"id_str"];
//   NSLog(@"%@", JSON);
//        
//        
//    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
//   NSLog(@"%@", error);
//    }];
//    [operation start];
 }


-(void) oAuthEngineAccessToken:(FOAuthEngine *)engine setAccessToken:(OAToken *)token {
    if ([token key] == nil)
    {
        [engine requestAccessToken];
    }else{
#if DEBUG
        NSLog(@"access token :%@", [token key]);
    
        [self sendUpdate:@"test" inReplyTo:0];
#endif
	}
}

- (void)oAuthEngineFailureAccessToken:(OAServiceTicket *)ticket data:(NSData *)data {
	[progressHUD hide:YES];
#if DEBUG
	NSLog(@"Can not get access token");
#endif
	
}

- (void)viewDidLoad {
	self.navigationController.navigationBarHidden = NO;
    [super viewDidLoad];
    
    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"TwitterLoginView" owner:self options:nil];
    
    self.view = [views objectAtIndex:0];

	// Do any additional setup after loading the view, typically from a nib.
	self.navigationItem.leftBarButtonItem = nil;
	self.navigationItem.hidesBackButton = YES;
	
	//Add skip button
//	self.navigationItem.rightBarButtonItem = [[WBarButtonItem alloc] initWithTitle:@"Skip" style:UIBarButtonItemStylePlain target:self action:@selector(skip:)];
//	[self.navigationItem.rightBarButtonItem setBackgroundImage:[UIImage imageNamed:kImageBarButtonBackground] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault ];
//	
//	//Add refresh button
//	WBarButtonItem *refreshButton = [[WBarButtonItem alloc] initWithTitle:@"Refresh" style:UIBarButtonItemStylePlain target:self action:@selector(refresh:)];
//	self.navigationItem.leftBarButtonItem = refreshButton;
	
    rdEngine = [[FTwitterOAuthEngine alloc] initWithDelegate:self];
	
	progressHUD.detailsLabelText = @"Opening twitter login page.";
    self.webBrowser.delegate = self;
    
    progressHUD = [[MBProgressHUD alloc] initWithView:self.view];
    progressHUD.dimBackground = YES;
	
	// Regiser for HUD callbacks so we can remove it from the window at the right time
	progressHUD.delegate = self;

    [self.view addSubview:progressHUD];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self refresh:nil];
	
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setWebBrowser:nil];
    [super viewDidUnload];
}

- (void)displayAuthorization {
    if( rdEngine.hasRequestToken ) {
        NSURLRequest * request = [rdEngine authorizationFormURLRequest];
#if DEBUG
		NSLog(@"Url request verified code: %@", [[request URL] absoluteString]);
#endif
        [self.webBrowser loadRequest:request];
		[progressHUD show:YES];
    } else {
		[self cannotConnectTwitter];
	}
}

#pragma mark UIWebViewDelegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
#if DEBUG
    NSLog(@"Failed to load page %@", error);
#endif
	[progressHUD hide:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	
#if DEBUG
	NSLog(@"request : %@", [[request URL] absoluteString]);
#endif
	[progressHUD show:YES];
	
	if ([[[request URL] absoluteString] isEqualToString:kTwitterApiSubmit]) {
		progressHUD.detailsLabelText = @"Authenticating...";
	}
	
	if ([rdEngine isOAuthCallBackURL:[[request URL] host]]) {
		progressHUD.detailsLabelText = @"Authenticating...";
		[progressHUD show:YES];
		
		
		NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
        NSArray *urlComponents = [[[request URL] absoluteString] componentsSeparatedByString:@"&"];
               
        for (NSString *keyValuePair in urlComponents)
        {
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents objectAtIndex:0];
            NSString *value = [pairComponents objectAtIndex:1];
            
            [queryStringDictionary setObject:value forKey:key];
        }
        
        [queryStringDictionary objectForKey:@"ad_eurl"];
		if ([queryStringDictionary objectForKey:@"denied"]) {
#if DEBUG
			NSLog (@"user clicked cancel button");
			
#endif
			//When user click cancel, occurs "skip" event
			[self userClickCancel];
			return NO;
		} else if ([queryStringDictionary objectForKey:@"oauth_verifier"]) {
			NSString *verifiedCode = [queryStringDictionary objectForKey:@"oauth_verifier"];
#if DEBUG
			NSLog (@"oauth_verifier %@",verifiedCode);
#endif
			
			[rdEngine setVerifier:verifiedCode];
			[rdEngine requestAccessToken];
			[progressHUD show:YES];
			return NO;
		}			
	}
	
	    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    //RDLOG(@"web view started loading");
}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[progressHUD hide:YES];
}

- (void)userClickCancel {
    
}

- (void)refresh:(id) sender {
	[progressHUD show:YES];
	[rdEngine requestRequestToken];
    [self displayAuthorization];
}

- (void)cannotConnectTwitter {
    [[[UIAlertView alloc] initWithTitle:@"Alert" message:@"Connecting to Twitter is fail." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show]; 
}

@end